﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Data.SqlClient;

public class clsEmail
{
    public clsEmail()
    {
        
    }

    public void Send_Email_with_attechement(string send_To, string message_Subject, string Message_body, System.IO.Stream Filepostion, string Filename,bool ishtml)
    {//setup mail
      MailMessage msg = new MailMessage();
        // send mail transfair protocal client
        SmtpClient smtp=new SmtpClient();

        try
        {
            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            //to get the info about your smtp from web configuration 
            System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

            msg.From = new MailAddress(settings.Smtp.Network.UserName);//from argument to get the info@YourWebSiteDomain.com

            string[] emillist = send_To.Split(','); // fu. to send multi reipicent 

            foreach (string address in emillist)
            {
                msg.To.Add(new MailAddress(address));
            }
            msg.Subject = message_Subject; //from argument subject mail
            
            msg.Attachments.Add(new Attachment(Filepostion, Filename)); //from argument to attachment file and get two  parameter file postion must be system.io.stream and file name must string
            
            msg.Body = Message_body; //from argument to get the message body

            msg.IsBodyHtml = ishtml;
            smtp = new SmtpClient(settings.Smtp.Network.Host); //to get Your SMTPServer

            smtp.Credentials = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password); //to get YourSMTPServerUserName, YourSMTPServerPassword
            
            smtp.Send(msg); //send mail 

        }

        catch (System.Net.Mail.SmtpFailedRecipientsException ex)
        { // Get the email that is causing email sending failed exception

            String emailCausingException = ex.FailedRecipient;

            // Take some action either re-send the email again or do some error handling code here

            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)

                {// Get the status code why and what is actually causing an email sending error

                    System.Net.Mail.SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;

                    if (status == SmtpStatusCode.MailboxBusy ||status == SmtpStatusCode.MailboxUnavailable)//to check if the mail box busy or unavailable
                    {

                        System.Threading.Thread.Sleep(5000); //to sleep the send and try again in 5sec=5000

                        smtp.Send(msg);//send again the message
                    }

                }
            }

        }

         catch (SmtpException smtpException)
        { // You can put a switch block to check for different exceptions or errors  

            // To check if the client is authenticated or is allowed to send email using the specified SMTP host

            if (smtpException.StatusCode == SmtpStatusCode.ClientNotPermitted)
                throw smtpException;

            // The following code checks if the email message is too large to be stored in destination mailbox

            if (smtpException.StatusCode == SmtpStatusCode.ExceededStorageAllocation)
                throw smtpException;

            // To check if the email was successfully sent to the SMTP service

            if (smtpException.StatusCode == SmtpStatusCode.Ok)
                throw smtpException;

            // When the SMTP host is not found check for the following value

            if (smtpException.StatusCode == SmtpStatusCode.GeneralFailure)
                throw smtpException;
        }
      

    }

    public void Send_Email_with_out_attechement(string send_To, string message_Subject, string Message_body, bool ishtml)
    {//setup mail
        MailMessage msg = new MailMessage();
        // send mail transfair protocal client
        SmtpClient smtp = new SmtpClient();

        try
        {
            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            //to get the info about your smtp from web configuration 
            System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

            msg.From = new MailAddress(settings.Smtp.Network.UserName);//from argument to get the info@YourWebSiteDomain.com

            string[] emillist = send_To.Split(','); // fu. to send multi reipicent 

            foreach (string address in emillist)
            {
                msg.To.Add(new MailAddress(address));
            }
            msg.Subject = message_Subject; //from argument subject mail

            msg.Body = Message_body; //from argument to get the message body

            msg.IsBodyHtml = ishtml;

            smtp = new SmtpClient(settings.Smtp.Network.Host); //to get Your SMTPServer

            smtp.Credentials = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password); //to get YourSMTPServerUserName, YourSMTPServerPassword

            smtp.Send(msg); //send mail 

        }

        catch (System.Net.Mail.SmtpFailedRecipientsException ex)
        { // Get the email that is causing email sending failed exception

            String emailCausingException = ex.FailedRecipient;

            // Take some action either re-send the email again or do some error handling code here

            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {// Get the status code why and what is actually causing an email sending error

                    System.Net.Mail.SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;

                    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)//to check if the mail box busy or unavailable
                    {

                        System.Threading.Thread.Sleep(5000); //to sleep the send and try again in 5sec=5000

                        smtp.Send(msg);//send again the message
                    }

                }
            }

        }

        catch (SmtpException smtpException)
        { // You can put a switch block to check for different exceptions or errors  

            // To check if the client is authenticated or is allowed to send email using the specified SMTP host

            if (smtpException.StatusCode == SmtpStatusCode.ClientNotPermitted)
                throw smtpException;

            // The following code checks if the email message is too large to be stored in destination mailbox

            if (smtpException.StatusCode == SmtpStatusCode.ExceededStorageAllocation)
                throw smtpException;

            // To check if the email was successfully sent to the SMTP service

            if (smtpException.StatusCode == SmtpStatusCode.Ok)
                throw smtpException;

            // When the SMTP host is not found check for the following value

            if (smtpException.StatusCode == SmtpStatusCode.GeneralFailure)
                throw smtpException;
        }


    }


    public System.Text.StringBuilder mail()
    {
        System.Text.StringBuilder mail_Builder=new System.Text.StringBuilder();
        
        string connection_string = WebConfigurationManager.ConnectionStrings["Test_Connection"].ConnectionString;
        
        SqlConnection connection = new SqlConnection(connection_string);
        
        SqlCommand cmd = new SqlCommand("Get_All_Emaill", connection);
        
        cmd.CommandType=CommandType.StoredProcedure;
        
        connection.Open();
        
        SqlDataReader reader = cmd.ExecuteReader();
        
        while(reader.Read())
        {
            mail_Builder.Append(reader[0]+",");
        }
       
        mail_Builder.Remove(mail_Builder.Length - 1, 1);

        return mail_Builder;

    }

        
    }



